package com.rchat.pocmini.activity.setting;

import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso.common.dialog.CustomDialog;
import com.aso.common.progress.FlikerProgressBar;
import com.aso.common.sp.SPHelper;
import com.aso.common.utils.ToastUtils;
import com.google.zxing.client.android.CaptureActivity;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.binddevice.BindDevicePresenterImpl;
import com.rchat.pocmini.activity.ble.BleActivity;
import com.rchat.pocmini.activity.changepwd.ChangePwdActivity;
import com.rchat.pocmini.activity.help.HelpActivity;
import com.rchat.pocmini.activity.login.LoginPresenterImpl;
import com.rchat.pocmini.activity.qrcode.QRCodeMvpActivity;
import com.rchat.pocmini.activity.qrcode.QRCodePresenterImpl;
import com.rchat.pocmini.activity.recharge.ReChargeMvpActivity;
import com.rchat.pocmini.bean2eventbus.EventBusLoginBean;
import com.rchat.pocmini.bean2eventbus.EventBusRemoteBean;
import com.rchat.pocmini.bean2eventbus.PowerWakeLockBean;
import com.rchat.pocmini.bluetooth.BTService;
import com.rchat.pocmini.common.mvp.BaseMvpActivity;
import com.rchat.pocmini.common.update.AppUpdateGlobal;
import com.rchat.pocmini.common.update.AppUpdateManager;
import com.rchat.pocmini.global.IntentKeyGlobal;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.service.RchatClientService;
import com.rchat.pocmini.util.SPUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by itsdf07 on 2017/8/19.
 */

public class SettingActivity extends BaseMvpActivity<SettingPresenterImpl, SettingModelImpl>
        implements SettingContract.View {
    @BindView(R.id.layout_back)
    View mLayoutBack;
    @BindView(R.id.item_plugins_download)
    RelativeLayout mItemPluginDownload;
    @BindView(R.id.item_help)
    View mItemHelp;
    @BindView(R.id.item_ble)
    View mItemBle;
    @BindView(R.id.item_location)
    View mItemLocation;
    @BindView(R.id.item_binddevice)
    View mItemBindDevice;
    @BindView(R.id.item_myqrcode)
    View mItemMyQrcode;
    @BindView(R.id.item_modifypwd)
    View mItemModifyPwd;
    @BindView(R.id.item_btconnect)
    View mItemBtConnect;
    @BindView(R.id.item_recharge)
    View mItemRecharge;
    @BindView(R.id.item_bind_rchatplus)
    View mItemRemotePlus;
    TextView mTvRemoteState;
    @BindView(R.id.widget_flikerbar)
    FlikerProgressBar mDownloadProgressBar;
    @BindView(R.id.tv_item_check_pluginversion)
    TextView mTvItemCheckPlugin;
    @BindView(R.id.tv_text)
    TextView mTvDownloadPlug;
    @BindView(R.id.item_check_appversion)
    View mItemCheck;
    @BindView(R.id.tv_item_check_appversion)
    TextView mTvItemCheck;
    @BindView(R.id.tv_item_power_wakelock)
    TextView mTvPowerWakeLock;


    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView() {
        ((TextView) mItemHelp.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_help));
        ((TextView) mItemBle.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_ble));
        ((TextView) mItemLocation.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_location));
//        ((TextView) mItemBindDevice.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_binddevice));
        ((TextView) mItemBindDevice.findViewById(R.id.tv_item_content)).setText(getString(R.string.text_activate));
        ((TextView) mItemMyQrcode.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_myqrcode));
        ((TextView) mItemModifyPwd.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_modifypwd));
        ((TextView) mItemBtConnect.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_btconnect));
        ((TextView) mItemRecharge.findViewById(R.id.tv_item_content)).setText(getString(R.string.item_text_recharge));
        mTvRemoteState = ((TextView) mItemRemotePlus.findViewById(R.id.tv_item_content));
        mTvDownloadPlug.setText(String.format(getString(R.string.item_text_down_rchatplus), getString(R.string.app_name)));

//        mItemPluginDownload.setVisibility(mPresenter.hasPlugin() ? View.GONE : View.VISIBLE);
//        mItemRemotePlus.setVisibility(mPresenter.hasPlugin() ? View.VISIBLE : View.GONE);
        if (mPresenter.hasPlugin()) {
            boolean keepAlive = (boolean) SPUtil.get(this, SPUtil.SPKeyGlobal.KEY_BIND_REMOTESERVICE, false);
            updateKeepAliveStatus(keepAlive);
        } else {
            updateKeepAliveStatus(false);
        }
        mTvItemCheck.setText(getString(R.string.item_text_check_appversion));
        int powerWakeLockStatus = SPHelper.getInteger(SPHelper.SPKeyGlobal.KEY_POWER_WAKELOCK);
        mTvPowerWakeLock.setText(powerWakeLockStatus == 1 ? "高性能模式" : "省电模式");

    }

    @Override
    public void doAfterInitView() {

    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (mPresenter.hasPlugin()){
//            initView();
//        }
    }

    @OnClick({R.id.layout_back,
            R.id.item_bind_rchatplus,
            R.id.item_help,
            R.id.item_ble,
            R.id.item_location,
            R.id.item_binddevice,
            R.id.item_plugins_download,
            R.id.item_myqrcode,
            R.id.item_modifypwd,
            R.id.item_btconnect,
            R.id.item_recharge,
            R.id.item_power_wakelock,
            R.id.item_check_appversion
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.item_bind_rchatplus:
                boolean bindRemoteState = (boolean) SPUtil.get(this, SPUtil.SPKeyGlobal.KEY_BIND_REMOTESERVICE, false);
                SPUtil.put(this, SPUtil.SPKeyGlobal.KEY_BIND_REMOTESERVICE, !bindRemoteState);
                updateKeepAliveStatus(!bindRemoteState);
                EventBusRemoteBean bean = new EventBusRemoteBean();
                bean.setCurrentEvent(!bindRemoteState ? EventBusRemoteBean.EVENT_STARTREMOTE : EventBusRemoteBean.EVENT_UNBINDREMOTE);
                bean.setTarget(this.getClass(), RchatClientService.class, "onEventBusDispatchRemote");
                EventBus.getDefault().post(bean);
                break;
            case R.id.item_help:
                startActivity(new Intent(this, HelpActivity.class));
                break;
            case R.id.item_ble:
                startActivity(new Intent(this, BleActivity.class));
                break;
            case R.id.item_location:
                mPresenter.showLocationMenu(this);
                break;
            case R.id.item_binddevice:
//                startActivity(new Intent(this, BindDeviceActivity.class));
                Intent intentActivate = new Intent(this, CaptureActivity.class);
                startActivityForResult(intentActivate, SettingPresenterImpl.REQUEST_CODE_ACTIVATE);
                break;
            case R.id.item_plugins_download:
//                if (mPresenter.isPluginDownloading()) {
//                    showShortToast("正在下载，请稍后");
//                    break;
//                }
//                mDownloadProgressBar.setVisibility(View.VISIBLE);
//                if (mDownloadProgressBar.getProgress() > 0) {
//                    mDownloadProgressBar.reset();
//                }
                mPresenter.checkUpdate(AppUpdateGlobal.CheckUpdateModel.PLUGIN);
//
//                if (mPresenter.isPluginDownloading()) {
//                    showShortToast("正在下载，请稍后");
//                    break;
//                }
//                CustomDialog.Builder builder = new CustomDialog.Builder(this);
//                builder.setMessage(getString(R.string.tip_plugin_download));
//                builder.setTitle(getString(R.string.tip));
//                builder.setInterceptBack(true);
//                builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        mDownloadProgressBar.setVisibility(View.VISIBLE);
//                        if (mDownloadProgressBar.getProgress() > 0) {
//                            mDownloadProgressBar.reset();
//                        }
//                        mPresenter.downloadPlugin();
//                    }
//                });
//
//                builder.setNegativeButton(getString(R.string.cancle),
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();

                break;
            case R.id.item_myqrcode:
                Intent intent = new Intent();
                intent.putExtra("code", QRCodePresenterImpl.QR_STRING_CODE_MY_USERNAME);
                intent.setClass(this, QRCodeMvpActivity.class);
                startActivity(intent);
                break;
            case R.id.item_modifypwd:
                Intent intentModifyPwd = new Intent();
                intentModifyPwd.putExtra("login", true);
                intentModifyPwd.setClass(this, ChangePwdActivity.class);
                startActivity(intentModifyPwd);
                break;
            case R.id.item_btconnect:
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                break;
            case R.id.item_recharge:
                Intent intentRecharge = new Intent(this, ReChargeMvpActivity.class);
                intentRecharge.putExtra(IntentKeyGlobal.IntentRecharge.INTENT_KEY_FROM, IntentKeyGlobal.IntentRecharge.INTENT_VALUE_RECHARGE);
                startActivity(intentRecharge);
                break;
            case R.id.item_power_wakelock:
                int powerWakeLockStatus = SPHelper.getInteger(SPHelper.SPKeyGlobal.KEY_POWER_WAKELOCK) == 1 ? 4 : 1;
                SPHelper.put(SPHelper.SPKeyGlobal.KEY_POWER_WAKELOCK, powerWakeLockStatus);
                mTvPowerWakeLock.setText(powerWakeLockStatus == 1 ? "高性能模式" : "省电模式");

                PowerWakeLockBean powerWakeLockBean = new PowerWakeLockBean();
                powerWakeLockBean.setCurrentEvent(powerWakeLockStatus == 1 ?
                        PowerWakeLockBean.EVENT_ACQUIRE_POWERWAKELOCK : PowerWakeLockBean.EVENT_RELEASE_POWERWAKELOCK);
                powerWakeLockBean.setTarget(this.getClass(), PocService.class, "onEventPowerWakeLock");
                EventBus.getDefault().post(powerWakeLockBean);
                break;
            case R.id.item_check_appversion:
                mPresenter.checkUpdate(AppUpdateGlobal.CheckUpdateModel.CHECK);
                break;
            default:
                break;
        }
    }

    @Override
    public void updateDownloadProgressBar(float progress) {
        mTvItemCheckPlugin.setText("已下载：" + progress + "%");
        if (progress >= 100) {
            mTvItemCheckPlugin.setText("");
        }
//        mDownloadProgressBar.setProgress(progress);
//        if (progress >= 100) {
//            mDownloadProgressBar.finishLoad();
//        }
    }

    @Override
    public void updateCheckUpdate(int progress) {
        mTvItemCheck.setText("已下载：" + progress + "%");
        if (progress >= 100) {
            mTvItemCheck.setText("");
        }
    }

    @Override
    public void updateKeepAliveStatus(boolean isKeepAlive) {
        mTvRemoteState.setText(isKeepAlive ? getString(R.string.item_text_bind_rchatplus) : getString(R.string.item_text_unbind_rchatplus));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data) {
            return;
        }
        String result = data.getStringExtra("scan_result");
        if (TextUtils.isEmpty(result)) {
            ToastUtils.showToast(this, "扫描的内容为空，请确认是否需要重新扫码");
            return;
        }
        ALog.d("result = %s", result);
        switch (requestCode) {
            case BindDevicePresenterImpl.REQUEST_CODE_ACTIVATE:
                if (resultCode == RESULT_OK) {
                    mPresenter.activate(result);
                }
                break;
            default:
                break;
        }
    }
}
